<template>
  <view class="use-from-page">
    <view class="w-686rpx mt-24rpx ml-32rpx use_from">
      <view class="a_wrap">
        <view class="a_item px-32rpx">
          <view
            class="bd_bottom py-26rpx flex flex-row justify-between items-center"
          >
            <view class="a_title"
              >姓名
              <text class="star">*</text>
            </view>
            <view class="flex flex-row items-center">
              <input
                class="a_input"
                placeholder-style="color:#999999"
                v-model="formData.name"
                :disabled="isDisabled"
                placeholder="请输入真实姓名"
              />
            </view>
          </view>
        </view>
        <view class="a_item px-32rpx">
          <view
            class="bd_bottom py-26rpx flex flex-row justify-between items-center"
          >
            <view class="a_title">证件类型<text class="star">*</text></view>
            <view class="flex flex-row items-center">
              <view class="a_title mr-20rpx">{{ idTypeName }}</view>
            </view>
          </view>
        </view>
        <view class="a_item px-32rpx">
          <view class="py-26rpx flex flex-row justify-between items-center">
            <view class="a_title">证件号<text class="star">*</text></view>
            <view class="flex flex-row items-center">
              <input
                data-type="idcard"
                type="idcard"
                class="a_input"
                placeholder-style="color:#999999"
                v-model="formData.idNumber"
                placeholder="请输入证件号"
                :disabled="isDisabled"
                @input="changeIdNumber"
              />
            </view>
          </view>
        </view>
      </view>
      <view class="a_wrap mt-24rpx">
        <view class="a_item px-32rpx">
          <view
            class="bd_bottom py-26rpx flex flex-row justify-between items-center"
          >
            <view class="a_title">手机号<text class="star">*</text></view>
            <view class="flex flex-row items-center">
              <input
                data-type="phone"
                maxlength="11"
                type="number"
                class="a_input"
                placeholder-style="color:#999999;"
                v-model="formData.phone"
                placeholder="请输入手机号"
              />
            </view>
          </view>
        </view>
        <view class="a_item px-32rpx">
          <view class="py-26rpx flex flex-row justify-between items-center">
            <view class="a_title">短信验证码<text class="star">*</text></view>
            <view class="flex flex-row items-center">
              <input
                maxlength="6"
                type="number"
                class="w-240rpx text-right text-30rpx lh-42rpx mr-24rpx"
                placeholder-style="color:#999999"
                v-model="formData.code"
                placeholder="请输入验证码"
              />
              <view
                v-if="countDownState.showCountDownBtn"
                @click="handleStartCountDown"
                class="w-104rpx h-60rpx lh-60rpx bg-primary text-center text-white text-28rpx border-rd-8rpx"
              >
                获取
              </view>
              <view
                v-else
                class="w-104rpx h-60rpx lh-60rpx bg-#cbcbcb text-center text-white text-28rpx lh-42rpx border-rd-8rpx"
              >
                {{ countDownState.count }}s
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="a_wrap mt-24rpx">
        <picker
          @change="relationChange"
          :value="formData.relationIndex"
          :range="relationEnum"
          range-key="name"
        >
          <view class="a_item px-32rpx">
            <view class="py-26rpx flex flex-row justify-between items-center">
              <view class="a_title">与本人关系</view>
              <view class="flex flex-row items-center">
                <input
                  type="text"
                  class="a_title mr-20rpx"
                  placeholder-style="color:#999999;"
                  :value="relationName"
                  placeholder="请选择"
                  disabled
                />
                <image
                  class="w-24rpx h-48rpx"
                  :src="specUrl('right_arrow.png')"
                ></image>
              </view>
            </view>
          </view>
        </picker>
      </view>
      <view class="a_wrap mt-24rpx">
        <picker
          @change="genderChange"
          :value="formData.genderIndex"
          :range="genderEnum"
          range-key="name"
          :disabled="isDisabled"
        >
          <view class="a_item px-32rpx">
            <view
              class="bd_bottom py-26rpx flex flex-row justify-between items-center"
            >
              <view class="a_title">性别</view>
              <view class="flex flex-row items-center">
                <view class="a_title mr-20rpx">{{ genderName }}</view>
                <image
                  v-if="!isDisabled"
                  class="w-24rpx h-48rpx"
                  :src="specUrl('right_arrow.png')"
                ></image>
              </view>
            </view>
          </view>
        </picker>
        <picker
          mode="date"
          :value="formData.birthday"
          :end="endDate"
          :disabled="isDisabled"
          @change="birthdayChange"
        >
          <view class="a_item px-32rpx">
            <view class="py-26rpx flex flex-row justify-between items-center">
              <view class="a_title">出生日期</view>
              <view class="flex flex-row items-center">
                <view class="a_title mr-20rpx">{{ formData.birthday }}</view>
                <image
                  v-if="!isDisabled"
                  class="w-24rpx h-48rpx"
                  :src="specUrl('right_arrow.png')"
                ></image>
              </view>
            </view>
          </view>
        </picker>
      </view>
      <view class="a_wrap mt-24rpx">
        <!-- <picker
            @change="genderChange"
            :value="formData.nationalityIndex"
            :range="nationalityEnum"
            range-key="name"
          > -->
        <view class="a_item px-32rpx">
          <view
            class="bd_bottom py-26rpx flex flex-row justify-between items-center"
          >
            <view class="a_title">国籍<text class="star">*</text></view>
            <view class="flex flex-row items-center">
              <view class="a_title mr-20rpx">{{ nationalityName }}</view>
              <!-- <image
                  class="w-24rpx h-48rpx"
                  :src="specUrl('right_arrow.png')"
                ></image> -->
            </view>
          </view>
        </view>
        <!-- </picker> -->
        <picker
          @change="nationChange"
          :value="formData.nationIndex"
          :range="nationEnum"
          range-key="name"
        >
          <view class="a_item px-32rpx">
            <view class="py-26rpx flex flex-row justify-between items-center">
              <view class="a_title">民族<text class="star">*</text></view>
              <view class="flex flex-row items-center">
                <view class="a_title mr-20rpx">{{ nationName }}</view>
                <image
                  class="w-24rpx h-48rpx"
                  :src="specUrl('right_arrow.png')"
                ></image>
              </view>
            </view>
          </view>
        </picker>
      </view>
      <view class="a_wrap mt-24rpx">
        <view class="a_item px-32rpx">
          <view
            class="bd_bottom py-26rpx flex flex-row justify-between items-center"
          >
            <view class="a_title">住址<text class="star">*</text></view>
            <view class="flex flex-row items-center">
              <uni-data-picker
                :clear-icon="false"
                v-model="formData.city"
                ellipsis
                :localdata="cityList"
                popup-title="所在地区"
                @change="handleCity"
              ></uni-data-picker>
            </view>
          </view>
        </view>
        <view class="a_item px-32rpx">
          <view class="py-26rpx flex flex-row justify-between items-center">
            <view class="a_title">详细地址<text class="star">*</text></view>
            <view class="flex flex-row items-center">
              <input
                class="a_input mr-20rpx"
                placeholder-style="color:#999999"
                v-model="formData.address"
                placeholder="请输入"
              />
            </view>
          </view>
        </view>
      </view>
    </view>
    <BottomButton @clickBtn="submit"> 确认添加 </BottomButton>
  </view>
</template>
<script setup>
  import { specUrl } from '@/utils/icon';
  import { ref, reactive, computed } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import healthCard from '../static/ElectronicHealthCard';
  import { HEALTH_CARD_TYPE } from '@/utils/healthCard/constant';
  import {
    genderEnum,
    idTypeEnum,
    nationEnum,
    nationalityEnum,
    relationEnum,
    cityJSON
  } from '../static/constant';
  import { getDateTime, startCountdown } from '@/utils/util';
  import { validateIdCard, validatePhone } from '@/utils/validate';
  import healthCardUtil from '@/utils/healthCard/index';
  import { patientDetail, sendCode } from '@/apis/patient';

  const authCode = ref('');
  const patientId = ref('');
  const cityList = cityJSON;

  onLoad(options => {
    console.log('[options]', options);
    authCode.value = options.authCode || '';
    patientId.value = options.patientId || '';
    loadPatientInfo();
  });
  // 是否可以修改
  const isDisabled = computed(() => {
    return patientId.value;
  });

  // 国籍默认:中国
  const defaultNationalityIndex = nationalityEnum.findIndex(
    it => it.value == 'CN',
  );
  // 民族默认:汉族
  const defaultNationIndex = nationEnum.findIndex(it => it.value == 1);

  const formData = ref({
    name: '',
    birthday: '',
    idTypeIndex: 0, // 证件类型默认:居民身份证
    idNumber: '',
    relationIndex: null,
    genderIndex: 0, // 性别默认:男
    phone: '',
    code: '',
    nationalityIndex: defaultNationalityIndex || 0,
    nationIndex: defaultNationIndex || 0,
    city: [
      { text: '四川省', value: '510000' },
      { text: '泸州市', value: '510500' },
      { text: '江阳区', value: '510502' },
    ],
    address: '', // 详细地址
  });

  // 身份证号
  const idTypeName = computed(() => {
    return idTypeEnum[formData.value.idTypeIndex].name;
  });
  const idType = computed(() => {
    return idTypeEnum[formData.value.idTypeIndex].value;
  });
  const changeIdNumber = e => {
    const { type } = e.currentTarget.dataset;
    const { value } = e.detail;
    if (
      type == 'idcard' &&
      idType.value == '01' &&
      value.length === 18 &&
      validateIdCard(value)
    ) {
      formData.value.genderIndex =
        parseInt(value.substr(16, 1)) % 2 == 1 ? 0 : 1;

      formData.value.birthday = value
        .substr(6, 8)
        .replace(/(.{4})(.{2})/, '$1-$2-');
    }
  };

  /* 性别 */
  const genderName = computed(() => {
    return genderEnum[formData.value.genderIndex].name;
  });

  const genderChange = e => {
    formData.value.genderIndex = e.detail.value;
  };

  // 生日
  const birthdayChange = e => {
    formData.value.birthday = e.detail.value;
  };

  // 最大选择日期
  const endDate = computed(() => {
    return getDateTime(new Date().getTime());
  });

  // 国家
  const nationalityName = computed(() => {
    return nationalityEnum[formData.value.nationalityIndex].name;
  });
  const nationality = computed(() => {
    return nationalityEnum[formData.value.nationalityIndex].value;
  });

  // 民族
  const nationName = computed(() => {
    return nationEnum[formData.value.nationIndex].name;
  });
  // const nation = computed(() => {
  //   return nationEnum[formData.value.nationIndex].value;
  // });

  const nationChange = e => {
    formData.value.nationIndex = e.detail.value;
  };

  const relationName = computed(() => {
    const relationInfo = relationEnum[formData.value.relationIndex];
    return relationInfo ? relationInfo.name : '';
  });
  const relation = computed(() => {
    const relationInfo = relationEnum[formData.value.relationIndex];
    return relationInfo ? relationInfo.value : '';
  });

  const relationChange = e => {
    formData.value.relationIndex = e.detail.value;
  };

  // 所在地区
  const handleCity = e => {
    console.log(e);
    formData.value.city = e.detail.value;
  };

  // 倒计时
  const DEFAULT_COUNT = 60;
  const countDownState = reactive({
    showCountDownBtn: true,
    count: DEFAULT_COUNT,
  });
  const handleStartCountDown = async () => {
    if (!validatePhone(formData.value.phone)) return;
    try {
      healthCardUtil.showLoad();
      const param = {
        phone: formData.value.phone,
        captchaType: 1,
      };
      await sendCode(param);
      healthCardUtil.hideLoad();
      countDownState.showCountDownBtn = false;

      startCountdown({
        duration: DEFAULT_COUNT,
        update: seconds => {
          countDownState.count = seconds;
        },
        finish: () => {
          countDownState.showCountDownBtn = true;
          countDownState.count = DEFAULT_COUNT;
        },
      });
    } catch (error) {
      healthCardUtil.hideLoad(1500);
    }
  };

  // 加载用户信息
  const loadPatientInfo = async () => {
    if (!patientId.value) return;
    try {
      healthCardUtil.showLoad();
      const { data } = await patientDetail(patientId.value);
      healthCardUtil.hideLoad();
      console.log(data, 'patientDetail');
      if (data) {
        const {
          name,
          birthday,
          idType,
          idNumber,
          gender,
          phone,
          city,
          address,
        } = healthCardUtil.transferInfoByPatientInfo(data);

        formData.value = {
          name,
          birthday,
          idTypeIndex: idTypeEnum.findIndex(it => it.value == idType),
          idNumber,
          genderIndex: genderEnum.findIndex(it => it.value == gender),
          phone,
          relationIndex: null, // 升级默认重新选择
          code: '',
          city,
          address,
          nationalityIndex: defaultNationalityIndex || 0,
          nationIndex: defaultNationIndex || 0,
        };

        console.log(formData.value, 'patientDetail');
      }
    } catch (error) {
      console.log(error, 'patientDetail');
      healthCardUtil.hideLoad(1500);
    }
  };
  function checkForm() {
    if (!formData.value.name) {
      healthCardUtil.toast('请输入姓名');
      return false;
    }
    if (!formData.value.idNumber) {
      healthCardUtil.toast('请输入证件号');
      return false;
    }
    if (!validateIdCard(formData.value.idNumber)) {
      return false;
    }
    if (!formData.value.phone) {
      healthCardUtil.toast('请输入手机号');
      return false;
    }
    if (!validatePhone(formData.value.phone)) {
      return false;
    }
    if (!formData.value.code) {
      healthCardUtil.toast('请输入验证码');
      return false;
    }
    if (!formData.value.address) {
      healthCardUtil.toast('请输入详细地址');
      return false;
    }
    return true;
  }
  // 提交
  const submit = async () => {
    console.log(formData.value);
    const checkFormResult = checkForm();
    if (!checkFormResult) return;
    try {
      healthCardUtil.showLoad();
      let param = {
        name: formData.value.name,
        gender: genderName.value,
        birthday: formData.value.birthday,
        idType: idType.value,
        idNumber: formData.value.idNumber,
        phone1: formData.value.phone,
        nation: nationName.value,
        relation: relation.value,
        address: JSON.stringify({
          city: formData.value.city,
          address: formData.value.address,
        }),
        ext: JSON.stringify({
          nationality: nationality.value,
        }),
      };
      console.log('【useFrom 参数】', param);
      await healthCard.createCard({
        param,
        code: formData.value.code,
        authCode: authCode.value,
        patientId: patientId.value,
      });
      healthCardUtil.hideLoad();
      uni.navigateTo({
        url: `/patientPages/healthCard/webview/index?type=${HEALTH_CARD_TYPE.BIND_VERIFY}`,
      });
    } catch (error) {
      healthCardUtil.hideLoad(1500);
    }
  };
</script>

<style lang="scss">
  .top_img {
    position: absolute;
  }
  .use_from {
    position: relative;
    @include safeAreaBottom(190rpx);
    .a_wrap {
      width: 100%;
      border-radius: 16rpx;
      background: #ffffff;
      .a_item {
        .a_title {
          position: relative;
          font-size: 30rpx;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: $uni-text-color;
          line-height: 42rpx;
          text-align: right;
          flex-shrink: 0;
          .star {
            position: absolute;
            top: 0;
            right: -20rpx;
            font-size: 30rpx;
            color: #ff4066;
          }
        }
        .a_input {
          text-align: right;
          font-size: 30rpx;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #333333;
          line-height: 42rpx;
        }
      }
    }
  }
  .bg-primary {
    background-color: var(--primary-my-color);
  }
</style>
